package com.xhji.web.mvc.response;

import com.xhji.web.mvc.exception.AbstractException;
import com.xhji.web.mvc.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;

import java.lang.reflect.Method;
import java.util.Objects;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static com.xhji.web.mvc.exception.ExceptionUtils.convertValidateException;

@Slf4j
public class DefaultResponseDecorate implements ResponseDecorate {

    private Environment environment;

    @Override
    public GenericResponse<Object> decorate(Object result, Throwable e, Method method) {
        GenericResponse<Object> warpObject = new DefaultGenericResponse<>();

        if (e != null) {
            warpObject.setCode(BAD_REQUEST.value());
            e = convertValidateException(e);
            warpObject.setMessage(e.getMessage());
            if (e instanceof AbstractException) {
                warpObject.setCode(((AbstractException) e).getCode());
            }
            if (e instanceof ValidationException) {
                warpObject.setDetails(((ValidationException) e).getFieldErrors());
            }
//            if (!environment.acceptsProfiles(Profiles.of("production"))) {
//                warpObject.setStackInfo(ExceptionUtils.getStackTrace(e));
//            }

            if(e instanceof DuplicateKeyException){
                warpObject.setMessage("数据已存在");
            }
        } else {
            warpObject.setCode(HttpStatus.OK.value());
        }
        warpObject.setData(result);
        if(Objects.nonNull(e)){
            log.error(e.getMessage(),e);
        }
        return warpObject;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

}
